<template>
	<view class="">
		<disHistory titleName="病害审核" compoType="bhsh" :beforeChange="beforeForm"
			@passSubmit="passSubmit" ref="shenheiRef"></disHistory>
	</view>
</template>

<script>
	import disHistory from '../../common/disHistory.vue'
	import mixins from '@/utils/mixins.js'
	import { diseaseOrderReview, diseaseOrderGetDetails } from "@/api/engineeringMaintenance/engineeringMaintenance.js"
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	import { uploadFile } from '@/utils/request'
	export default {
		name: 'approval',
		mixins: [mixins],
		components: {
			disHistory
		},
		data() {
			return {
				detailObj: {},
				beforeForm: {},
				requestStatus:false,
				isRequest:false
			}
		},
		methods: {
			passSubmit(obj, booleanValue) {
				console.log(obj, booleanValue, '父组件值')
				this.$set(obj, 'isAdopt', booleanValue)
				if(obj && obj.videoFileList && obj.videoFileList.length > 0){
					const taskArr = obj.videoFileList.filter(it => it.uploadStatus)
					if(taskArr.length > 0) {
						uni.showToast({
							title:'视频上传中,请稍等',
							icon:'none',
							mask:true
						})
						return
					}
				}
				if(this.requestStatus) return
				this.requestStatus = true
				// 删除视频记录的视频id
				let arr = [...obj.removeFileSet] || []
				if(arr.length) {
					 doc_deleteAttachs(arr)
				}
				diseaseOrderReview({
					...obj
				}).then(res => {
					if (res.success) {
						this.isRequest = true
						uni.showToast({
							title: res.message,
							icon: 'none',
							mask: true,
						})
						setTimeout(() => {
							uni.navigateBack()
							this.requestStatus = false
						}, 1600)
					}else {
						this.requestStatus = false
					}
				})
			},
			/**
			 * 获取到docId中的图片并且拼成网络路径格式
			 * @param {Number} docId
			 * @return {String} //拼好的网络路径格式
			 */
			async getItemImage(docId) {
				console.log('传进来的文档id', docId, this.$config.IMG_FILE_URL);
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let imgResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'image')
						resolve(imgResult.map(it => ({
							url: this.$config.IMG_FILE_URL + it.fileName,
							id: it.id
						})));
					}).catch(err => reject(err))
				})
			},
			async getVideoList(docId) {
				console.log('传进来的文档id', docId, this.$config.IMG_FILE_URL);
				return await new Promise((resolve, reject) => {
					getPicture({
						docId
					}).then(res => {
						let videoResult = res.result.filter(item => item.contentType.substring(0, item
							.contentType.indexOf("/")) === 'video')
						resolve(videoResult.map(it => ({
							url: this.$config.VIDEO_URL + it.fileName,
							id: it.id
						})));
					}).catch(err => reject(err))
				})
			}
		},
		onLoad(params) {
			let imgs
			let obj_img
			let videoList
			if (params && params.id) {
				this.mileage = params.type
				console.log(this.mileage,'----')
				diseaseOrderGetDetails({
					id: params.id
				}).then(async res => {
					// console.log(res,'详情未修复')
					if (res.success) {
						this.detailObj = res.result
						this.$set(this.detailObj,'diseaseGrade',res.result.diseaseGradeName)
						if (res.result.docId) {
							imgs = await this.getItemImage(res.result.docId)
							this.$set(this.detailObj, 'fileListImg', imgs)
							this.detailObj.sourceImgs = JSON.parse(JSON.stringify(imgs))
						}
						if (res.result.videoDocId) {
							let video = await this.getVideoList(res.result.videoDocId)
							this.$set(this.detailObj, 'videoFileList', video)
							this.detailObj.sourceVideos = JSON.parse(JSON.stringify(video))
						}
						if(res.result.diseaseOrderLogDto.docId) {
							obj_img = await this.getItemImage(res.result.diseaseOrderLogDto.docId)
						}
						if(res.result.diseaseOrderLogDto.videoDocId) {
							videoList = await this.getVideoList(res.result.diseaseOrderLogDto.videoDocId)
						}
						let obj_dto = res.result.diseaseOrderLogDto
						this.$set(obj_dto, 'mileage',this.mileage)
						//变更病害前对象(用同样的绑定值修改上面会影响到下面(例如备注等字段))
						this.beforeForm = {
							startMileage: this.getContent2(obj_dto),
							remark: obj_dto.diseaseRemarks,
							ringNumber: `${obj_dto.startNumber || ''}${obj_dto.startNumber && obj_dto.endNumber ? '-' : ''}${obj_dto.endNumber || ''}`,
							otherPosition: obj_dto.others,
							clockPosition: obj_dto.clockwisePosition,
							nowStatus: obj_dto.diseaseStatus,
							level: obj_dto.diseaseGradeName + (obj_dto.diseaseNo ? obj_dto.diseaseNo : ''),
							imgs: obj_img || [],
							videos:videoList || [],
							measure:obj_dto.repairMethod,
							createDate:obj_dto.createDate,
							createUserName:obj_dto.createUserName,
							inspectUser:obj_dto.inspectUser
						}
						// console.log(obj_dto.diseaseGradeName,'对象');
						this.$set(this.detailObj, 'updateIds', [])
						this.$set(this.detailObj, 'updateVideoIds', [])
						this.detailObj.removeFileSet = new Set()
						this.$refs.shenheiRef.historyForm = this.detailObj
					}
				})

			}
		},
		async beforeDestroy() {
			if(!this.isRequest) {
				console.error('销毁钩子函数22',this.detailObj)
				// 新加图片后没有点击操作按钮直接退出 需要删除新加的id
				let needDelIds = [], needDelIds2 = []
				if(this.detailObj.updateIds.length) {
					let ids = this.detailObj.sourceImgs.map(i => i.id)
					needDelIds = this.getDifference(ids, this.detailObj.updateIds)
					
				}
				// 删除视频
				if(this.detailObj.updateVideoIds.length) {
					let ids = this.detailObj.sourceVideos.map(i => i.id)
					needDelIds2 = this.getDifference(ids, this.detailObj.updateVideoIds)
				}
				let allIds = [].concat(needDelIds, needDelIds2)
				if(allIds.length) {
					await doc_deleteAttachs(allIds)
				}
				// 找出删除的数据 原数据和现在的数组对比,并上传
				let result = this.getArrDifSameValue(this.detailObj.fileListImg, this.detailObj.sourceImgs || [])
				console.error(result)
				if(result.length) {
					let base64List = []
					let dataList = []
					for(let it of result) {
						const base64_img = await urlTobase64(it.url)
						base64List.push(base64_img.split(",")[1])
					}
					// 水印数据
					let formData = {}
					//区间/站点
					formData.name = this.detailObj.lineSiteSectionName
					//里程
					const distance = this.getContent2(this.detailObj)
					//环号
					const startRing = this.detailObj.startNumber || ''
					const endRing = this.detailObj.endNumber || ''
					const others = this.detailObj.others || ''
					const timeClock = this.detailObj.clockwisePosition || ''
					formData.ring =
						`${distance}${distance && startRing ? ',' : ''}${startRing}${startRing && endRing ? '~' : '' }${endRing}${(distance && others)||(endRing && others) ? ',' : ''}${others}${(distance && timeClock)  ||  (startRing && endRing && timeClock) || (others&&timeClock)  ? ',' : ''}${timeClock}`
					//现状
					formData.status = this.detailObj.diseaseStatus || ''
					formData.dateTime = this.getDate2(new Date)
					let response = await uploadImageFromBase64({
						dataList:[formData.name, formData.ring, formData.status, formData.dateTime],
						docId:this.detailObj.docId,
						base64List
					})
					console.error(response, '结果')
				}
				
				//找出删除的视频并且重新上传
				// let result2 = this.getArrDifSameValue(this.detailObj.videoFileList, this.detailObj.sourceVideos || [])
				// console.log(result2, '视频文件')
				// if(result2.length) {
				// 	for(let item of result2) {
				// 		uni.downloadFile({
				// 			url: item.url,
				// 			success: async (res) => {
				// 				if (res.statusCode === 200) {
				// 					console.error(res,'下载成功');
				// 					// #ifdef MP-WEIXIN
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						name: 'attach',
				// 						filePath: res.tempFilePath,
				// 						isOffline: true
				// 					}
				// 					// #endif
									
				// 					// #ifdef APP-PLUS || H5
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.detailObj.videoDocId, },
				// 						files: [{
				// 							name: "attach",
				// 							uri: res.tempFilePath
				// 						}],
				// 						isOffline: true
				// 					}
				// 					// #endif
				// 					let data = await uploadFile(uploadResq)
				// 					console.error(data, '165行上传视频')
				// 				}
				// 			}
				// 		});
				// 	}
				// }
			}
			
		},
	}
</script>

<style lang="scss" scoped>

</style>
